<template>
  <div class="hisapply_container">
    <AppLayoutSidebar>
      <!-- <div class="modal_mask" v-if="isShowMask"  @click="closePoperver"></div> -->
      <template slot="sidebar">
        <ApplyHis
          v-if="btnActive===1 || btnActive===3"
          ref="applyHis"
          :check-url.sync="checkUrl"
          @checkPostMsg="checkPostMsg"
          @refreshIframe="isRefresh"
        />
        <ApplyCheck
          v-if="btnActive===2"
          ref="applyCheck"
          @applyCheckEmit="applyCheckPostMsg"
        />
        <div class="apply_navs">
          <div class="type_navs">
            <!-- ======================tab切换按钮================================== -->
            <div
              class="abtn"
              v-for="item in btnOptions"
              :key="item.type"
              :class="{btn_active: btnActive === item.type}"
              @click="btnTypeChange(item.type)">
              <div class="btn_txt noSelect">{{item.label}}</div>
            </div>
          </div>
          <div class="btn_right flex flex-row justify-end w-100" style="padding-bottom: 10px;" v-if="btnActive === 2">
            <template v-if="applyfile">
              <el-popover
                placement="top-start"
                title=""
                width="40"
                trigger="hover"
              >
                <div class="file_navs">
                  <div class="file_nav fc_red" @click="applyFileDel">删除</div>
                </div>
                <el-image
                  slot="reference"
                  style="width: 28px; height: 28px;vertical-align: top;"
                  :src="applyfile"
                  :preview-src-list="srcList">
                </el-image>
              </el-popover>
            </template>
            <div class="flex flex-row align-center" style="z-index: 2000020;">
              <div class="popoverBox flex flex-row align-center" @click="closePoperver" v-if="isShowMask">
                <i class="el-icon-circle-close" style="color: #999; font-size: 18px; margin-bottom: 1px;"></i>
                <span class="fs-14 mar-l-3">登记信息若有修改，请重新点击→</span>
              </div>
              <el-button class="mar-l-10" style="padding: 8px 8px !important;" size="mini" type="primary" @click="applyCheckPostMsgSearch">号源查询</el-button>
            </div>
            <div class="flex flex-row align-center">
              <el-button class="mar-l-10" style="padding: 8px 8px !important;" size="mini" type="success" @click="clearAllInfo" v-if="isClearAll">清空</el-button>
            </div>
          </div>
          <div class="btn_right_setting" v-permission="'YJYY10008041'" v-if="isOpenAuthInSetBtn || applyInfoHospital=='fuding'">
            <CheckConfigSetting
              :hospital-code="hospitalCode"
              :config-visible.sync="configVisible"
            />
          </div>
          <div class="btn_right_setting" v-else>
            <CheckConfigSetting
              :hospital-code="hospitalCode"
              :config-visible.sync="configVisible"
            />
          </div>
        </div>
      </template>
      <!-- active==2检查这里 -->
      <div
        class="main_box scroll-y"
        ref="main_box"
        :style="{'padding-bottom': '100px', 'height': mainBoxHeight + 'px'}"
        slot="main"
        v-if="btnActive===3">
        <!-- 已预约列表 -->
        <AppointedHISList ref="AppointedHISListRef"></AppointedHISList>
      </div>
      <div
        slot="main"
        class="main_box"
        v-else>
        <div class="check_app_iframe_box">
          <CheckIframe
            id="checkIFrame"
            ref="CheckIframe"
            v-if="checkUrl && clinicalConfig"
            :check-url.sync="checkUrl"
            style="height: calc(100vh - 50px)"
            :iframe-config="clinicalConfig"
            @iframePMBack="iframePMBack"
          />
        </div>
      </div>
    </AppLayoutSidebar>
    <!-- 拍照 -->
    <cameraPhoto ref="cameraDlg" :row="row"></cameraPhoto>
  </div>
</template>

<script>
/* eslint-disable */
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage' // removeLocalStorage
import { getIsShowTwoList, debounce } from '@/utils/utils'
import AppLayoutSidebar from '@/components/appLayoutSidebar'
import CheckIframe from '@/views/iframe/checkAppointment'
import CheckConfigSetting from '@/components/appConfig/check/checkRegistrationConfig'
import cameraPhoto from '@/components/appCamera/cameraPhoto'
import ApplyHis from './applyHIS'
import ApplyCheck from './applyCheck'
import AppointedHISList from '../appointQuery/sourceEnquiry/index.vue'
// import HisRecordDialog from './hisRecordDialog'
const CHECK_FORM_DEFAULT_KEY = 'CHECK_FORM_DEFAULT'
const CHECK_APPLY_FILE_KEY = 'CHECK_APPLY_FILE'
import { mapGetters } from 'vuex'
import { MessageBox } from 'element-ui'
import bus from '@/api/bus'
import store from '@/store'
export default {
  components: {
    CheckConfigSetting,
    ApplyHis,
    ApplyCheck,
    AppointedHISList,
    CheckIframe,
    cameraPhoto,
    // HisRecordDialog,
    AppLayoutSidebar
  },
  data() {
    return {
      isShowMask: false,
      row: {
        applyHospitalCode: '',
        accessionNo: ''
      },
      applyInfoHospital: window.g.applyInfoHospital,
      mainBoxHeight: 800,
      isClearAll: window.g.isFilterMerge, // 清空按钮
      isShowApplyCheck: window.g.IS_APPLYCHECK_PICKHIS, // 玉环特有的人民医院需要手工选择his记录
      loading: false,
      configVisible: false,
      userName: this.$store.state.user.userName,
      userCode: this.$store.state.user.userCode,
      hospitalCode: this.$store.state.user.hospitalCode,
      hospitalName: this.$store.state.user.hospitalName,
      btnActive: 1, // 1HIS申请、2手动登记、3已预约列表
      btnOptions: !window.g.isApplyListOrderFront ? [
        { label: 'HIS申请', type: 1 },
        { label: '手动登记', type: 2 },
        { label: '已预约列表', type: 3 }
      ] : [],
      // checkTimer: null,
      // 检查预约
      appoint_type: window.g.APPOINT_TYPE || '前台登记', // 预约类型
      appoint_url: window.g.APPOINT_URL ? window.g.APPOINT_URL + '/index.html?isLogo=1' : '',
      dialogCheckAppoVisible: false,
      checkUrl: '', // window.g.APPOINT_URL ? window.g.APPOINT_URL + '/index.html?isLogo=1&yeFlag=1' : ''
      applyfile: null,
      isShowTwoList: false
    }
  },
  computed: {
    ...mapGetters(['hisActivedIndex', 'rowCurr']),
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    clinicalConfig() {
      return this.$store.state.settings.clinicalContent
    },
    isCloseAutoRetract() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isCloseAutoRetract) || false
    },
    CheckApplyShow() {
      let _show = true
      if (this.appConfig && this.appConfig.baseConfig && typeof this.appConfig.baseConfig.applyCheckRegister === 'boolean') {
        _show = this.appConfig.baseConfig.applyCheckRegister
      }
      return !window.g.checkConfigNotApi && _show
    },
    checkConfigBtnShow() {
      let _show = true
      if (this.appConfig && this.appConfig.baseConfig && typeof this.appConfig.baseConfig.checkConfigBtnShow === 'boolean') {
        _show = this.appConfig.baseConfig.checkConfigBtnShow
      }
      return !window.g.checkConfigNotApi && _show
    },
    // 附件是否显示
    applyCheckFileSHow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.applyCheckFileSHow
    },
    isHideGreenCheck() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isHideGreenCheck
    },
    isGreenCheckAddAuth() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isGreenCheckAddAuth
    },
    isOpenAuthInSetBtn() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isOpenAuthInSetBtn
    },
    // isShowTwoList() {
    //   return this.appConfig &&
    //     this.appConfig.baseConfig &&
    //     this.appConfig.baseConfig.isShowTwoList
    // },
  },
  async created() {
    this.isShowTwoList = getIsShowTwoList()
    // console.log('apply created=>this.isShowTwoList', this.isShowTwoList)
    // 黄石要根据权限配置 his申请和 手动登记单
    if (window.g.isApplyListOrderFront) {
      if (this.$hasPermission(['YJYY10008038'])) {
        this.btnOptions.push({ label: 'HIS申请', type: 1 })
        this.btnActive = 1 || this.hisActivedIndex
      }
      if (this.$hasPermission(['YJYY10008039'])) {
        this.btnOptions.push({ label: '手动登记', type: 2 })
        this.btnOptions.length === 1 && (this.btnActive = 2 || this.hisActivedIndex)
      }
      // 黄石医院默认也给加上已预约列表
      this.btnOptions.push({ label: '已预约列表', type: 3 })
    } else {
      // console.log('apply->this.isShowTwoList', this.isShowTwoList)
      if (this.isShowTwoList) {
        this.btnActive = 3 || this.hisActivedIndex
      } else {
        this.btnActive = 1 || this.hisActivedIndex
      }

      const tokenInfoString = localStorage.getItem('JJYY_SET_TOKENINFO')
      if (tokenInfoString && tokenInfoString.indexOf('applyDepartment') > 0) {
        const tokenInfo = JSON.parse(tokenInfoString)
        if (tokenInfo.applyDepartment) {
          this.btnOptions =  [
            { label: 'HIS申请', type: 1 },
            // { label: '手动登记', type: 2 },
            { label: '已预约列表', type: 3 }
          ]
        }
      } else {
        if (this.isHideGreenCheck) {
          this.btnOptions =  [
            { label: 'HIS申请', type: 1 },
            // { label: '手动登记', type: 2 },
            { label: '已预约列表', type: 3 }
          ]
        }
        if (this.isGreenCheckAddAuth) {
          this.btnOptions =  []
          this.btnOptions.push({ label: 'HIS申请', type: 1 })
          if (this.$hasPermission(['YJYY10008039'])) {
            this.btnOptions.push({ label: '手动登记', type: 2 })
          }
          // 黄石医院默认也给加上已预约列表
          this.btnOptions.push({ label: '已预约列表', type: 3 })
        }
      }
    }
    store.dispatch('patient/setHisActivedIndex', this.btnActive)
    // 是否显示已预约列表
    // if (window.g.isShowAppointedList) {
    //   this.btnOptions.push({ label: '已预约列表', type: 3 })
    //   this.btnOptions.length === 1 && (this.btnActive = 3 || this.hisActivedIndex)
    // }
    if (this.btnOptions.length === 0) {
      this.$message.info('请找管理员为您设置检查登记权限');
    }
    const checkFormDefault = getLocalStorage(CHECK_FORM_DEFAULT_KEY)
    if (checkFormDefault) {
      const cfd = JSON.parse(checkFormDefault)
      this.appoint_type = cfd.appoint_type
    }
    if (!this.isCloseAutoRetract) {
      this.$store.dispatch('app/closeSideBar', { withoutAnimation: false })
    }

    setTimeout(() => {
      if (document.getElementById('checkIFrame')) {
        this.checkUrl = window.g.APPOINT_URL
      }
    }, 1000 * 15)
    // 定时器，vue对象嵌套太深，只能写在window对象下，方便清除。
    window.timeForRefresh = setInterval(() => {
/*      if (!window.g.lcVERSION) {
        let newjs = window.sendJSONPRequest(window.g.APPOINT_URL + '/versionHandler.js', 'getLcVersion')
        newjs.onload = () => {
          if(window.g.isLcUpdate){
            this.$message.info('临床预约正在更新中，请耐心等待');
            this.checkUrl = '';
            setTimeout(() => {
              this.checkUrl = this.getCheckUrl()
            }, 1000)
          }
        }
      }*/
      window.checkNewVersion(() => {
        MessageBox.confirm('发现有新版本,请立即升级', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'warning'
        }).then(() => {
          window.location.reload(true)
        })
      },() => {
        this.$message.info('临床预约正在更新中，清耐心等待');
        this.checkUrl = '';
        setTimeout(() => {
          this.checkUrl = this.getCheckUrl()
        }, 1000)
      })
    }, 1000 * 60 * 10)
  },
  mounted() {
    this.mainBoxHeight = this.getClientHeight()
    bus.$off('checkPostMsg')
    bus.$on('checkPostMsg', (data) => {
      console.log('checkPostMsg=========>data', data)
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
    })
    // 黄石有时候默认是手动登记
    if (this.btnActive == 2) {
      this.checkUrl = this.getCheckUrl()
    }
    // bus.$off('switchTab')
    // bus.$on('switchTab', (data) => {
    //   this.btnTypeChange(data)
    // })
  },
  methods: {
    closePoperver() {
      this.isShowMask = false
      const userPhone = this.$store.state.user.userInfo.userPhone
      console.log('userPhone', userPhone)
      setLocalStorage(`isClickAppoSearchPover${userPhone}`, 1)
    },
    clearAllInfo () {
      this.$refs.applyCheck && this.$refs.applyCheck.resetInfo()
    },
    isRefresh(data) {
      console.warn('isRefresh')
      let refreshIframe = {}
      refreshIframe['refreshIframe'] = data
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(refreshIframe, '*')
    },
    getClientHeight() {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
      	var clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight:document.documentElement.clientHeight
      } else {
      	var clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight:document.documentElement.clientHeight
      }
      return clientHeight
    },
    getCheckUrl() {
      let registerRoom = getLocalStorage('UserPermision') || ''
      let string = this.appoint_url + `&v=${window.g.lcVERSION || window.g.VERSION}&yeFlag=1&hospitalCode=${this.hospitalCode}&hospitalName=${this.hospitalName}&operateUser=${this.userName}&operateCode=${this.userCode}&appointmentType2=${this.appoint_type || ''}&appointmentType=${this.appoint_type || ''}`
      if (registerRoom) {
        string += '&registerRoom=' + registerRoom
      }
      string += '&patientId='
      return string
    },
    checkPostMsg(data) {
      console.warn('checkPostMsg---->')
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
    },
    iframePMBack(data) {
      // console.error('来这里了', data)
      if (data.type === 4) {
        let row = {
          applyHospitalCode: data.dataParam.applyHospitalCode,
          accessionNo: data.dataParam.accessNo
        }
        this.row = row
        this.$nextTick(() => {
          this.openCamera()
        }, 200)
      }
      if (this.btnActive === 2) {
        this.applyFileDel()
        this.$nextTick(() => {
          this.$refs.applyCheck && this.$refs.applyCheck.iframePMBack(data)
        })
      } else {
        this.$nextTick(() => {
          this.$refs.applyHis && this.$refs.applyHis.iframePMBack(data)
        })
      }
    },
    applyCheckPostMsg(data) {
      this.checkPostMsg(data)
      if (this.applyfile && data.patientId && this.applyCheckFileSHow) {
        // 附件上传，存存储本地，演示用
        let fileObj = getLocalStorage(CHECK_APPLY_FILE_KEY)
        fileObj = fileObj ? JSON.parse(fileObj) : {}
        fileObj[`${data.patientId}`] = this.applyfile
        setLocalStorage(CHECK_APPLY_FILE_KEY, JSON.stringify(fileObj))
      }
    },
    applyCheckPostMsgSearch() {
      this.$refs.applyCheck && this.$refs.applyCheck.appointmentPostMessage()
    },
    // 摄像头拍照弹框
    openCamera() {
      if (this.$refs.cameraDlg) {
        this.$refs.cameraDlg.cameraDlgOpen()
      }
    },
    // 摄像头拍照
    cameraPhoto(file) {
      this.applyfile = file
      this.srcList = [file]
    },
    applyFileDel() {
      this.applyfile = ''
      this.srcList = []
    },
    btnTypeChange(type) {
      this.btnActive = type
      store.dispatch('patient/setHisActivedIndex', type)
      if (type === 1 || type === 2) {
        this.checkUrl = ''
        this.checkUrl = this.getCheckUrl()
        if (type === 1) {
          console.log('tabChangeToOne防抖')
          bus.$emit('tabChangeToOne')
          // debounce(() => {
          //   console.log('tabChangeToOne防抖')
          //   bus.$emit('tabChangeToOne')
          // }, 200)
        }
        if (type === 2) {
          const userPhone = this.$store.state.user.userInfo.userPhone
          const isClickAppoSearchPover = getLocalStorage(`isClickAppoSearchPover${userPhone}`)
          if (isClickAppoSearchPover == 1) {
            this.isShowMask = false
          } else {
            this.isShowMask = true
          }
        }
      } else if (type == 3) {
        setTimeout(() => {
          console.log('this.rowCurr', this.rowCurr)
          bus.$emit('selectedRowCurr', this.rowCurr)
        }, 300)
      }
    }
  },
  beforeDestroy() {
    getLocalStorage('hisActivedIndex') && store.dispatch('patient/setHisActivedIndex', 1)
    bus.$off('checkPostMsg')
    clearInterval(window.timeForRefresh)
  },
  destroyed() {
    // bus.$off('selectedRowCurr')
    if (!this.$store.state.app.sidebar.opened) {
      this.$store.dispatch('app/toggleSideBar')
    }
  }
}
</script>

<style lang="scss" scoped>
$activeColor: #ff7600;
$defaultColor: #fff;
.hisapply_container{
  padding: 0;
  margin: 0;
  position: relative;
  background-color: #f9f9f9;
}
.apply_navs{
  width: 100%;
  min-height: 30px;
  position: absolute;
  bottom: 0px;
  left: 0;
  z-index: 1;
  // overflow: hidden;
  padding: 5px 20px 0;
  // background-color: rgba(255,255,255,0.7);
  // padding-top: 4px;
  .type_navs{
    display: flex;
  }
  .abtn{
    width: 114px;
    height: 34px;
    border-left: solid 1px #dfdedd;
    // border-right: 0;
    border-radius: 6px;
    transform: skew(-30deg);
    // margin-left: 20px;
    margin-bottom: -6px;
    overflow: hidden;
    padding-right: 12px;
  }
  .btn_txt{
    transform: skew(30deg);
    text-align: center;
    color: #7c7c7c;
    border-radius: 6px;
    border-top: solid 1px #dfdedd;
    border-right: solid 1px #dfdedd;
    line-height: 28px;
    height: 40px;
    margin-left: -5px;
    padding-left: 10px;
    cursor: pointer;
    background-color: #fff;
    &:hover{
      color:$activeColor;
    }
  }
  .btn_active.abtn {
    border-color: $activeColor;
  }
  .btn_active .btn_txt {
    border-color: $activeColor;
    color: #fff;
    background-color: $activeColor;
  }
  .btn_right{
    padding-right: 30px;
    position: absolute;
    // right: 6px;
    // top: 2px;
    // left: 20px;
    bottom: 30px;
    z-index: 1000;
  }
  .btn_right_setting{
    position: absolute;
    // right: 6px;
    // top: 2px;
    right: 20px;
    bottom: 2px;
    z-index: 1000;
  }
}
.file_navs{
  text-align: center;
  .file_nav{
    padding: 2px 0;
    cursor: pointer;
    &:hover{
      background-color: #ffd8b7;
    }
  }
}
.main_box{
  // overflow-y: scroll;
}
.popoverBox{
  z-index: 20000 !important;
  background-color: #fff;
  color: #666;
  padding: 8px 10px;
  border-radius: 6px;
  border: 1px dotted #f0f0f0;
  position: relative;
  cursor: pointer;
}
// .closeBtn{
//   z-index: 10002;
//   position: absolute;
//   right: 0px;
//   top: -25px;
//   font-size: 24px;
//   color: #fff;
// }
.modal_mask{
  z-index: 10000;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
}
</style>
